<template>
  <div>
    <!--面包屑导航区-->
    <!--<el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>-->
    <my-bread level1="权限管理" level2="角色列表"></my-bread>
    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoleDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom', idx1 === 0 ? 'btop' : '', 'vmiddle']" v-for="(item1,idx1) in scope.row.children" :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row :class="['vmiddle', idx2 === item1.children.length-1 ? '' : 'bdbottom']" v-for="(item2,idx2) in item1.children" :key="item2.id">
                  <!-- 渲染二级权限 -->
                  <el-col :span="6">
                    <el-tag closable type="success" @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 渲染三级权限 -->
                    <el-tag closable v-for="(item3) in item2.children" type="warning"
                     :key="item3.id" @close="removeRightById(scope.row,item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <span v-if="scope.row.children.length === 0">未分配权限</span>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditRoleDialog(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeRoleById(scope.row.id)">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="showAllotRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightsDialogVisible"
     width="50%" @close="setRightsDialogClosed">
      <!--
        树形结构
        data -> 数据源 []
        show-checkbox -> 选择框
        node-key 每个节点的唯一标识 通常是data数据源中key名id
        default-expand-all 全部展开
        default-checked-keys [要选择的节点的id]
        props 配置项 {label,children}
            label节点的文字标题和children节点的子节点
            值都来源于data绑定的数据源中的该数据的key名 'label'和'children'
      -->
      <el-tree :data="rightsList" :props="treeProps" show-checkbox default-expand-all
       node-key="id" :default-checked-keys="defKeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addRoleDialogVisible" width="50%" @close="addRoleDialogClosed">
      <el-form :model="addRoleForm" :rules="addRoleRules" ref="addRoleRef" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog title="编辑角色" :visible.sync="editRoleDialogVisible" width="50%" @close="editRoleDialogClosed">
      <el-form :model="editRoleForm" :rules="editRoleRules" ref="editRoleRef" label-width="80px">
        <el-form-item label="角色ID">
          <el-input v-model="editRoleForm.roleId" readonly></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表
      rolesList: [],
      // 控制分配权限对话框显示与隐藏
      setRightsDialogVisible: false,
      // 权限列表
      rightsList: [],
      // 树形控件绑定数据
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 存储三级权限id
      defKeys: [],
      roleId: '',

      // 控制添加角色对话框显示与隐藏
      addRoleDialogVisible: false,
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      addRoleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 控制编辑角色对话框显示与隐藏
      editRoleDialogVisible: false,
      editRoleForm: {},
      editRoleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
      console.log(this.rolesList)
    },
    // 根据id删除对应权限
    async removeRightById(role, rightId) {
      // 弹窗提示用户是否删除
      const confirmRes = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      // 删除指定角色的权限
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败!!!')
      }
      // console.log(res) // 返回删除权限更新后的指定角色数据
      // this.getRolesList() 会重新获取数据重新渲染
      role.children = res.data // 只重新渲染相应角色数据
    },
    // 分配权限事件处理函数
    async showAllotRightDialog(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败')
      }

      this.rightsList = res.data
      console.log(this.rightsList)
      // 获取当前角色下面所有的三级权限
      this.getLeafKeys(role, this.defKeys) // 直接更新页面数据
      console.log(this.defKeys)
      /*
        let arrtemp = []
        role.children.forEach(item1 => { // for嵌套
          // arrtemp.push(item1.id)
          item1.children.forEach(item2 => {
            // arrtemp.push(item2.id)
            item2.children.forEach(item3 => {
              arrtemp.push(item3.id)
            })
          })
        })
        this.defKeys = arrtemp
      */
      this.setRightsDialogVisible = true
    },
    // 获取角色下对应的所有三级权限id ——递归判断
    getLeafKeys(node, arr) {
      // 如果当前节点不包含children属性 则是三级权限
      if (!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 监听对话框关闭事件 清空数组
    setRightsDialogClosed() {
      this.defKeys = []
    },
    // 点击为当前角色分配权限
    async allotRights() {
      // roles/roleId/rights 请求体中rid=>'101,116' 全选/半选id数组组成的字符串
      // ES6 展开运算符 ...数组或者对象
      const idArr = [...this.$refs.treeRef.getCheckedKeys(), // 返回目前被选中的节点的 key 所组成的数组
        ...this.$refs.treeRef.getHalfCheckedKeys()] // 返回目前半选中的节点的 key 所组成的数组
      const idStr = idArr.join(',')

      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }

      this.$message.success('分配权限成功')
      // 刷新角色列表
      this.getRolesList()

      this.setRightsDialogVisible = false
    },

    // 添加角色
    addRole() {
      this.$refs.addRoleRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败')
        }

        this.$message.success('添加角色成功')
        // 刷新角色列表
        this.getRolesList()
        this.addRoleDialogVisible = false
      })
    },
    // 监听添加角色对话框的关闭
    addRoleDialogClosed() {
      this.$refs.addRoleRef.resetFields()
    },
    // 显示编辑角色对话框
    async showEditRoleDialog(id) {
      const { data: res } = await this.$http.get(`roles/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色信息失败')
      }

      this.editRoleForm = res.data
      this.editRoleDialogVisible = true
    },
    // 监听编辑角色对话框的关闭
    editRoleDialogClosed() {
      this.$refs.editRoleRef.resetFields()
    },
    // 编辑提交角色
    editRole() {
      this.$refs.editRoleRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`roles/${this.editRoleForm.roleId}`, this.editRoleForm)
        if (res.meta.status !== 200) {
          return this.$message.error('编辑角色失败')
        }

        this.$message.success('编辑角色成功')
        // 刷新角色列表
        this.getRolesList()
        this.editRoleDialogVisible = false
      })
    },
    // 根据id删除角色
    async removeRoleById(id) {
      const confirmRes = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消删除操作')
      }
      const { data: res } = await this.$http.delete(`roles/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败')
      }

      this.$message.success('删除角色成功')
      // 刷新角色列表
      this.getRolesList()
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 8px;
}

.btop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vmiddle {
  display: flex;
  align-items: center;
}
</style>
